package cn.yy.cloudpay.cardread;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TwoLineListItem;

import com.alibaba.fastjson.JSON;
import com.android.usbport.USBManager;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.newland.mtype.DeviceRTException;
import com.newland.mtype.ModuleType;
import com.newland.mtype.ProcessTimeoutException;
import com.newland.mtype.event.DeviceEvent;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.cardreader.CardReader;
import com.newland.mtype.module.common.cardreader.CommonCardType;
import com.newland.mtype.module.common.cardreader.K21CardReader;
import com.newland.mtype.module.common.cardreader.K21CardReaderEvent;
import com.newland.mtype.module.common.cardreader.OpenCardReaderResult;
import com.newland.mtype.module.common.light.IndicatorLight;
import com.newland.mtype.module.common.light.LightType;
import com.newland.mtype.module.common.rfcard.RFCardType;
import com.newland.mtype.module.common.scanner.BarcodeScanner;
import com.newland.mtype.module.common.scanner.ScannerListener;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.yy.cloudpay.R;
import cn.yy.cloudpay.activity.BaseActivity;
import cn.yy.cloudpay.activity.PayActivity;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.cardread.N900Device;
import cn.yy.cloudpay.common.iface.ResultVo;
import cn.yy.cloudpay.listener.ITitlebarClickListener;
//import cn.yy.cloudpay.usb.ComNUtil;
import cn.yy.cloudpay.usb.ComUtil_N;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.CountDownTimer;
import cn.yy.cloudpay.util.ObjectGenerator;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.util.WebserviceRequset;
import cn.yy.cloudpay.view.LoadingDialog;
import cn.yy.cloudpay.view.TitlebarLayout;
import cn.yy.cloudpay.view.ToastUtil;
import com.newland.mtype.module.common.cardreader.SearchCardRule;

/**
 * 二维码扫描Activity
 * @author yy-01
 *
 */
public class FeixiScanT2Activity extends BaseActivity {
	public Logger log= Logger.getLogger(this.getClass());

	private TitlebarLayout titlebar;
	private RelativeLayout relativeLayout;
	private Context mContext;
	private Activity activity;
	// 显示支付金额+
	private TextView mTvAmount;
	private TextView mTvDownTimer;
	private ImageView mIvPic;
	private BarcodeScanner scanner;
	private CloudPayApplication mApplication;
	private static Integer SCAN_TIME = 60; // 扫描器运行时长（秒）
	//	private MyCountDownTimer mc;
	private IndicatorLight light;

	private PopupWindow popupWindow;
	private ArrayAdapter<UsbSerialPort> mAdapter;
	private List<UsbSerialPort> mEntries = new ArrayList<UsbSerialPort>();

	private K21CardReader cardReader;
	private boolean isPress = false;
	private String paycode="";
	private int equiment=0;	//1:待机，2:运行中
	private TextView statesStr;
	private TextView tv_activity_warn;
	private TextView tv_command;
	private TextView tv_com;
	private View view;
	private boolean initFocus = true;
	public int ix=20;
	public int startix = 600;
	public int stopix = 20;
	public int startin = 300;
	public int startwin = 600;
	public int startoin = 300;
	public boolean is_send=false;
	public boolean is_send_statrt = false;
	public boolean isCheck = true;

	public LoadingDialog mProgress;
	public String dialog_msg = "重启扫描";
	public int what_ = 0;
	private String state = "";
	private String from = "0";
	private BigDecimal price;
	private ImageView iv_layout_titlebar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scancode);
		from = "0";
		mContext = this;
		activity = this;
		mApplication = (CloudPayApplication) getApplication();
		initView();
	}

	private void initView() {
		iv_layout_titlebar = (ImageView)findViewById(R.id.iv_layout_titlebar);
		mTvAmount = (TextView) findViewById(R.id.tv_activity_scancode_amuont);
		mTvDownTimer = (TextView) findViewById(R.id.tv_activity_scancode_downtime);
		mIvPic = (ImageView) findViewById(R.id.iv_activity_scancode_pic);
		relativeLayout = (RelativeLayout) findViewById(R.id.titlebar_activity_scancode);
		statesStr = (TextView)findViewById(R.id.tv_status);
		tv_activity_warn = (TextView)findViewById(R.id.tv_activity_warn);
		tv_command = (TextView)findViewById(R.id.tv_command);
		tv_com = (TextView)findViewById(R.id.tv_com);
		mTvDownTimer.setText("扫码/刷卡(测试)");

		mProgress = new LoadingDialog(mContext, "正在支付，请稍后");
		mTvAmount.setText("欢迎使用飞洗无人洗车");
		mIvPic.setImageResource(R.drawable.feixi);
		mIvPic.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				deviceHandler.sendEmptyMessage(MESSAGE_REFRESH);
//				openDeviceList();
			}
		});
		iv_layout_titlebar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if("1".equals(mApplication.isMT())) {
					light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
				}
				if(cardReader!=null){
					cardReader.cancelCardRead();
				}
				stopScanner();
				finish();
			}
		});

		if("1".equals(mApplication.isMT())) {
			light = (IndicatorLight) mApplication.getDeviceInstance().getStandardModule(ModuleType.COMMON_INDICATOR_LIGHT);
		}

		titlebar = new TitlebarLayout(mContext, relativeLayout, "请使用二维码付款");
		titlebar.setTitlebarClickListener(new ITitlebarClickListener() {
			@Override
			public void OnRetrunListener(View view) {
				finish();
			}
		});

		view = LayoutInflater.from(mContext).inflate(R.layout.usbserial_list_activity, null);

		N900Device n900Device = N900Device.getInstance(this,mApplication);
		cardReader = n900Device.getCardReaderModuleType();
		deviceHandler.sendEmptyMessage(MESSAGE_REFRESH);
		startPay();
	}

	private void startPay(){
		new Handler().postDelayed(new Runnable(){
			public void run() {
				light.turnOnLight(new LightType[]{LightType.GREEN_LIGHT});
				runScanner();
				openCardReader();
			}
		}, 2000);
	}

	private void stopPay(){
		light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
		stopScanner();
		cardReader.cancelCardRead();
	}

	/*
	 * 初始化扫描器
	 */
	private void initModule() {
		scanner = mApplication.getScanner();
		scanner.initScanner(this);
	}

	private final int CARD_PAY = 0x0002;
	public void openBankcard(){
		from = "1";
		Intent intent = new Intent();
		intent.setAction("com.ys.smartpos.pay.sdk");
		intent.putExtra("transType", 1046);
		intent.putExtra("amount", 1);
		intent.putExtra("discountAmount", 1);
		intent.putExtra("displayReadCardBg",false);
		intent.putExtra("orderId", StringUtil.genseq());
		intent.putExtra("pkgName", FeixiScanT2Activity.this.getPackageName());
		intent.putExtra("targetClassName","cn.yy.cloudpay.cardread.GetAmountActivity");
		startActivityForResult(intent, CARD_PAY);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			from = "0";
			switch (requestCode) {
				case CARD_PAY: // 支付
					int result = data.getExtras().getInt("transResult", -1);
					if(result==0){
						stopCheck();
						log.info("支付成功,打开设备-414");
						Long amount =data.getLongExtra("amount", 0l);    // 金额
						String pan = data.getStringExtra("pan");    // 卡号
						String bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
						String authCode = data.getStringExtra("authCode");    //借贷记标识
						if (pan == null) pan = "";
						if (bankCardType == null) bankCardType = "";

						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType, "1", amount.toString(),authCode);
					}else {
						log.error("支付失败："+result);
						playBeepSoundAndVibrate(R.raw.fail);
						ToastUtil.showToast(mContext, "支付失败", ToastUtil.FAIL);
						startScannerHandler("支付失败");
					}
					break;
				default:
					break;
			}
		}catch(Exception ex){
			log.info(" 返回异常　" + requestCode + " " + resultCode+" ",ex);
		}
	}

	private void openCardReader() {
		if(from=="99"){
			cardReader.cancelCardRead();
			return;
		}
		from = "0";
		stopScanner();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					log.info("请刷卡或者插入IC卡...");
					final long beginTime = System.currentTimeMillis();
					cardReader.openCardReader(new ModuleType[] { ModuleType.COMMON_SWIPER, ModuleType.COMMON_ICCARDREADER, ModuleType.COMMON_RFCARDREADER }, true, SCAN_TIME, TimeUnit.SECONDS, new DeviceEventListener<K21CardReaderEvent>() {
						@Override
						public void onEvent(K21CardReaderEvent openCardReaderEvent, Handler handler) {
							OpenCardReaderResult cardResult = openCardReaderEvent.getOpenCardReaderResult();
							CommonCardType[] openedModuleTypes = null;
							if (cardResult == null || (openedModuleTypes = cardResult.getResponseCardTypes()) == null || openedModuleTypes.length <= 0) {
//								log.info("卡信息为null");
							} else if (openCardReaderEvent.isSuccess()) {
								from = "1";
								stopPay();
								playBeepSoundAndVibrate(R.raw.f0);
								log.info("读卡成功");
								ComUtil_N.instance(mContext).checkPay(0); //========================
//								openBankcard();
								long endTime = System.currentTimeMillis();
								log.info("耗时：" + (endTime - beginTime));
							} else if (openCardReaderEvent.isUserCanceled()) {
								log.info("取消开启读卡器");
							} else if (openCardReaderEvent.isFailed()) {
								if (openCardReaderEvent.getException() instanceof ProcessTimeoutException) {
									log.info("超时");
								}
								if (openCardReaderEvent.getException().getCause() instanceof ProcessTimeoutException) {
									log.info("超时w");
								}
								log.info("读卡器开启失败");
							}
						}

						@Override
						public Handler getUIHandler() {
							return null;
						}
					}, SearchCardRule.RFCARD_FIRST);
				} catch (Exception e) {
					e.printStackTrace();
					log.info("读卡器开启异常：");
					log.info(e.getMessage());
				}
			}
		}).start();
	}
	/*
	 * 运行扫描器
	 */
	private void runScanner() {
		if(from=="99"){
			stopScanner();
			return;
		}
		paycode = "";
		initModule();
		try {
			scanner.startScan(SCAN_TIME, TimeUnit.SECONDS, new ScannerListener() {
				@Override
				// 异步
				public void onResponse(String[] result) {
					from = "0";
					stopCheck();
					stopPay();
					String str = result[0];
					paycode = str;
					playBeepSoundAndVibrate(R.raw.f0);
                    ComUtil_N.instance(mContext).checkPay(1);  //==========================
//					sendPay();
				}

				@Override
				public void onFinish() {
					if(StringUtil.isEmpty(paycode)&&!"1".equals(from)) {
						stopPay();
						mHandler.sendEmptyMessage(3);
					}
				}
			});
		}catch (DeviceRTException ex){
			ex.printStackTrace();
		}
	}

	public void sendPay(){
		Message msg = new Message();
		msg.what = 1;
		mHandler.sendMessage(msg);
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:
					pay();
					break;
				case 3:
					startPay();
					break;
				case 4:
					statesStr.setText(state);
				default:
					break;
			}
		}
	};

	private void pay(){
		isPress = true;
		playBeepSoundAndVibrate(R.raw.beep); // 播放音频
		PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
		task.execute(paycode);
		isPress = false;
	}

	//洗车结束，启动闪付
	public void startScannerHandler(String msg){
		if(!StringUtil.isEmpty(msg)){
			dialog_msg = msg;
		}
		startPay();
		statesStr.setText("设备就绪，重新开始");
	}

	private void startScanner(){
		statesStr.setText("设备就绪，重新开始");
		tv_command.setText("");
		mProgress = new LoadingDialog(mContext, dialog_msg);
		mProgress.show();
	}

	public void display(String str){
		state = str;
		mHandler.sendEmptyMessage(4);
	}

	/*
	 * 展示支付金额
	 */
	private Spanned getAmountText() {
		Intent intent = getIntent();
		String amountString = intent.getStringExtra(Constant.PARAM_AMOUNT);
		String amount = "支付金额：" + amountString + "元";
		return Html.fromHtml(amount);
	}

	private MediaPlayer mediaPlayer;
	// 音量大小
	private static final float BEEP_VOLUME = 10.0f;
	// 震动时长
	private static final long VIBRATE_DURATION = 200L;
	// 是否震动
	private boolean vibrate = true;
	private boolean playBeep = true;

	/*
	 * 初始化音频
	 */
	private void initBeepSound(int avi) {
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		if (mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 使用系统铃声
			// mediaPlayer = MediaPlayer.create(this,
			// RingtoneManager.getActualDefaultRingtoneUri(this,
			// RingtoneManager.TYPE_NOTIFICATION));
			mediaPlayer.setOnCompletionListener(beepListener);
			mediaPlayer.setOnErrorListener(erroListener);
			AssetFileDescriptor file = getResources().openRawResourceFd(
					avi);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				// //使用系统铃声，不再调用prepare（）方法
				mediaPlayer.prepare();
			} catch (Exception e) {
				mediaPlayer = null;
			}
		}
	}

	/*
	 * 播放音频
	 */
	public void playBeepSoundAndVibrate(int avi) {
		releaseMedia();
		if(mediaPlayer==null){
			initBeepSound(avi);
		}
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}


	private static final int MESSAGE_REFRESH = 101;
	private static final int EQUIMENT_REFRESH = 102;
	private static final long EQUIMENT_TIMEOUT_MILLIS = 3000;

	private int l = 0;
	public Handler deviceHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_REFRESH:
					refreshDeviceList(view);
					break;
				case EQUIMENT_REFRESH:
					if(what_==103){
						deviceHandler.removeMessages(EQUIMENT_REFRESH);
					}else{
                        ComUtil_N.instance(mContext).checkState();
						deviceHandler.sendEmptyMessageDelayed(EQUIMENT_REFRESH, EQUIMENT_TIMEOUT_MILLIS);
					}
					break;
				default:
					super.handleMessage(msg);
					break;
			}
		}

	};

	private void openDeviceList(){
		ViewGroup vg = (ViewGroup)this.getWindow().getDecorView();
//		view = LayoutInflater.from(mContext).inflate(R.layout.usbserial_list_activity, null);
//		deviceHandler.sendEmptyMessage(MESSAGE_REFRESH);
		final ListView dlg_list = (ListView) view.findViewById(R.id.deviceList);
		mAdapter = new ArrayAdapter<UsbSerialPort>(this,
				android.R.layout.simple_expandable_list_item_2, mEntries) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final TwoLineListItem row;
				if (convertView == null){
					final LayoutInflater inflater =
							(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					row = (TwoLineListItem) inflater.inflate(android.R.layout.simple_list_item_2, null);
				} else {
					row = (TwoLineListItem) convertView;
				}

				final UsbSerialPort port = mEntries.get(position);
				final UsbSerialDriver driver = port.getDriver();
				final UsbDevice device = driver.getDevice();

				final String title = String.format("Vendor %s Product %s",
						device.getVendorId(),
						(short) device.getProductId());
				row.getText1().setText(title);

				final String subtitle = driver.getClass().getSimpleName();
				row.getText2().setText(subtitle);

				return row;
			}
		};
		dlg_list.setAdapter(mAdapter);
		dlg_list.setOnItemClickListener(new ListView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				log.info("选择：Pressed item " + position);
				if (position >= mEntries.size()) {
					log.info("提示：Illegal position.");
					return;
				}
				boolean ret = USBManager.getInstance(mContext).openUsbPort(mEntries.get(0));
				if(ret) {
					log.info("打开成功");
					Toast.makeText(mContext, "打开成功", Toast.LENGTH_SHORT).show();
					tv_com.setText("串口连接成功");
					popupWindow.dismiss();
//					deviceHandler.sendEmptyMessage(EQUIMENT_REFRESH);
				}else {
					log.info("打开失败");
					tv_com.setText("串口连接失败");
					Toast.makeText(mContext, "打开失败", Toast.LENGTH_SHORT).show();
				}
			}
		});
//		if(popupWindow == null){
		popupWindow = new PopupWindow(vg, ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		//设置窗体的内容
		popupWindow.setContentView(view);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//		}
		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
			public void onDismiss() {
				deviceHandler.removeMessages(MESSAGE_REFRESH);
				initFocus = false;
				setBackgroundAlpha(1.0f);
			}
		});
		setBackgroundAlpha(0.5f);
		popupWindow.showAtLocation(vg, Gravity.CENTER, 0, 10);
//		popupWindow.showAsDropDown(vg);
	}

	public void setBackgroundAlpha(float bgAlpha) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = bgAlpha;
		getWindow().setAttributes(lp);
	}

	private void refreshDeviceList(View v) {
		final ProgressBar mProgressBar = (ProgressBar)v.findViewById(R.id.progressBar);
		mProgressBar.setVisibility(View.VISIBLE);

		new AsyncTask<Void, Void, List<UsbSerialPort>>() {
			@Override
			protected List<UsbSerialPort> doInBackground(Void... params) {
				log.info("刷新设备列表");
				SystemClock.sleep(1000);
				return USBManager.getInstance(mContext).listUsbPort();
			}

			@Override
			protected void onPostExecute(List<UsbSerialPort> result) {
				mEntries.clear();
				mEntries.addAll(result);
//				mAdapter.notifyDataSetChanged();
				mProgressBar.setVisibility(View.INVISIBLE);
				log.info("查找结束:Done refreshing, " + mEntries.size() + " entries found.");
				if(mEntries.size()==0){
//					Toast.makeText(mContext, "没有连接串口", Toast.LENGTH_SHORT).show();
					ToastUtil.showToast(mContext, "没有连接串口", ToastUtil.WARNING);
					tv_com.setText("没有连接串口");
				}else{
					open();
				}
			}
		}.execute((Void) null);
	}

	public void open(){
		UsbManager usbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
		for(UsbSerialPort usb:mEntries) {
			if (usbManager.hasPermission(usb.getDriver().getDevice())) {
				deviceHandler.removeMessages(MESSAGE_REFRESH);
				boolean ret = USBManager.getInstance(mContext).openUsbPort(usb);
				if (ret) {
					log.info(usb.getPortNumber()+" 打开成功");
					Toast.makeText(mContext, "打开成功", Toast.LENGTH_SHORT).show();
					tv_com.setText("串口连接成功");
				} else {
					log.info(usb.getPortNumber()+" 打开失败");
					tv_com.setText("串口连接失败");
					Toast.makeText(mContext, "打开失败", Toast.LENGTH_SHORT).show();
				}
			}else{
				openDeviceList();
			}
		}
	}
	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
			releaseMedia();
		}
	};

	private final OnErrorListener erroListener = new OnErrorListener() {
		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			releaseMedia();
			return false;
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		from = "99";
		light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
		if(cardReader!=null){
			cardReader.cancelCardRead();
		}
		stopScanner();
	}

	/**
	 * 停止扫描器
	 */
	private void stopScanner() {
		scanner.stopScan();
	}

	/*
	 * 释放硬件资源
	 */
	private void stopModule() {
		if (scanner != null) {
			stopScanner();
//			Log.e("TAG", "调用stopScanner方法");
		}
	}

	/*sc
	 * 释放音频资源
	 */
	private void releaseMedia() {
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
//			Log.e("TAG", "释放音频资源");
		}
	}


	// 支付宝或微信支付异步任务
	public class PayAsyncTask extends AsyncTask<String, Void, String> {

		private ObjectGenerator generator = new ObjectGenerator(mContext);

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgress = new LoadingDialog(mContext, dialog_msg);
			mProgress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			String jsonStr = "";
			String rs = "";
			try {
				jsonStr = generator.getScanPayReqStr(Constant.PAY_TYPE_FEIXIPAY,0, mApplication.getOperator(), params);
				rs = WebserviceRequset.requsetService(jsonStr,mApplication.getServiceAddress());
			} catch (Exception e) {
				e.printStackTrace();
				log.error("网络请求异常："+jsonStr,e);
			}
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgress.dismiss();
			//如果支付成功，关闭扫描页面
			JSONObject resultJSON = null;
			Message message = new Message();
			try {
				if("anyType{}".equals(result)){
					message.obj = "返回值anyType{}:获取不到服务器证书文件";
					message.what = Constant.BUSINESS_ERROR;
				}else{
					resultJSON = new JSONObject(result);
					String resultCode = resultJSON.getString("result");
					String returnMsg = resultJSON.getString("return_msg");
					message.obj = returnMsg;
					if(resultCode.equals("SUCCESS")) {
						message.what = Constant.BUSINESS_SUCCESS;
					}else if(resultCode.equals("FAIL")) {
						message.what = Constant.BUSINESS_FAILED;
					}else if(resultCode.equals("WAIT")) {
						message.what = Constant.BUSINESS_WAIT;
					}else {
						message.what = Constant.BUSINESS_ERROR;
					}
					light.turnOnLight(new LightType[]{LightType.GREEN_LIGHT});
				}
			} catch (JSONException e) {
				e.printStackTrace();
				log.error("网络请求异常："+result,e);
				message.obj = "数据解析错误";
				message.what = Constant.BUSINESS_ERROR;
			} finally {
				mPayHandler.sendMessage(message);
			}
		}
	};

	public void checkState(){
		ix = 20;
		what_ = 102;
		deviceHandler.sendEmptyMessage(EQUIMENT_REFRESH);
	}

	public void stopCheck(){
		what_ = 103;
		log.info("停止实时检测");
		deviceHandler.sendEmptyMessage(EQUIMENT_REFRESH);
	}

	public void sendMsg(){
		log.info("设备发出警告");
	}

	@SuppressLint("HandlerLeak")
	private Handler mPayHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case Constant.BUSINESS_SUCCESS :
					//支付成功，查询是否洗车，打开机器
					log.info("支付成功,打开设备-414");
					playBeepSoundAndVibrate(R.raw.success);
                    ComUtil_N.instance(mContext).startup(ComUtil_N.write_1);	//===============================
//					startScannerHandler("支付成功");
					ToastUtil.showToast(mContext, "支付成功", ToastUtil.SUCCESS);
					break;
				case Constant.BUSINESS_FAILED : // 支付失败
				case Constant.BUSINESS_ERROR : // 支付失败
				case Constant.BUSINESS_WAIT : // 支付失败
					log.error("支付异常："+msg);
					playBeepSoundAndVibrate(R.raw.fail);
					startScannerHandler("支付异常："+msg);
					break;
				default:
					break;
			}
		}
	};

	public TextView getStatesStr() {
		return statesStr;
	}

	public TextView getTv_activity_warn() {
		return tv_activity_warn;
	}

	public TextView getTv_command() {
		return tv_command;
	}

	public int getEquiment() {
		return equiment;
	}

	public void setEquiment(int equiment) {
		this.equiment = equiment;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		CloudPayApplication.from = 1;
		if("1".equals(mApplication.isMT())) {
			light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
		}
		if(cardReader!=null){
			cardReader.cancelCardRead();
			cardReader.closeCardReader();
		}
		stopScanner();
	}

}
